package org.example.erat.model.export;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.List;

public class ExcelExportStrategy implements ExportStrategy {
    @Override
    public void exportStatistics(File file,
                                Map<String, List<String>> studentStatistics,
                                Map<String, List<String>> experimentStatistics) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建学生统计工作表
            Sheet studentSheet = workbook.createSheet("学生统计");
            createStudentSheet(studentSheet, studentStatistics);

            // 创建实验统计工作表
            Sheet experimentSheet = workbook.createSheet("实验统计");
            createExperimentSheet(experimentSheet, experimentStatistics);

            // 写入文件
            try (FileOutputStream fos = new FileOutputStream(file)) {
                workbook.write(fos);
            }
        }
    }

    private void createStudentSheet(Sheet sheet, Map<String, List<String>> studentStatistics) {
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("学号");
        headerRow.createCell(1).setCellValue("缺交次数");
        headerRow.createCell(2).setCellValue("缺交实验列表");

        // 填充数据
        int rowNum = 1;
        for (Map.Entry<String, List<String>> entry : studentStatistics.entrySet()) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(entry.getKey());

            List<String> stats = entry.getValue();
            if (stats.size() >= 2) {
                row.createCell(1).setCellValue(Integer.parseInt(stats.get(0))); // 缺交次数
                row.createCell(2).setCellValue(stats.get(1));                   // 缺交实验列表
            }
        }

        // 自动调整列宽
        for (int i = 0; i < 3; i++) {
            sheet.autoSizeColumn(i);
        }
    }

    private void createExperimentSheet(Sheet sheet, Map<String, List<String>> experimentStatistics) {
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("实验名");
        headerRow.createCell(1).setCellValue("缺交人数");
        headerRow.createCell(2).setCellValue("缺交学生列表");

        // 填充数据
        int rowNum = 1;
        for (Map.Entry<String, List<String>> entry : experimentStatistics.entrySet()) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(entry.getKey());

            List<String> stats = entry.getValue();
            if (stats.size() >= 2) {
                row.createCell(1).setCellValue(stats.get(0));
                row.createCell(2).setCellValue(stats.get(1));
            }
        }

        // 自动调整列宽
        for (int i = 0; i < 3; i++) {
            sheet.autoSizeColumn(i);
        }
    }
}